<?php

/**
 * Url helper with a fluent interface.
 *
 * @author    Mon Zafra <monzee at gmail>
 * @copyright (c)2009 Mon Zafra
 * @license   http://mz-project.googlecode.com/svn/trunk/LICENSE    MIT License
 * @version   SVN: $Id: UrlTo.php 29 2009-05-14 15:35:03Z monzee $
 * @todo Make this a part of the Mz library
 */
class Crud_View_Helper_UrlTo extends Zend_View_Helper_Abstract
{
    protected $_params = array();
    protected $_route = null;
    protected $_dirty = false;

    /**
     * Constructor.
     *
     * @param string $route
     */
    public function __construct($route = null)
    {
        $this->urlTo($route);
    }

    /**
     * A new instance is returned every time this is called.
     *
     * @param string $route        Route to use
     * @param bool   $pullDefaults Whether to use the default action,
     *                             controller and method from the
     *                             request object
     * @return Crud_View_Helper_UrlTo
     */
    public function urlTo($route = null, $pullDefaults = false)
    {
        if ($this->_dirty) {
            $helper = new self($route);
            $helper->setView($this->view);
            return $helper;
        }

        $this->_route = $route;
        if ($pullDefaults) {
            $req = Zend_Controller_Front::getInstance()->getRequest();
            $this->_params['action'] = null === $action ? $req->getActionName() : $action;
            $this->_params['controller'] = null === $controller ? $req->getControllerName() : $action;
            $this->_params['module'] = null === $module ? $req->getModuleName() : $module;
        }

        $this->_dirty = true;
        return $this;
    }

    /**
     * Sets a url parameter.
     *
     * @param string $param
     * @param mixed  $val
     * @return Crud_SimpleUrl
     */
    public function setParam($param, $val)
    {
        $this->_params[$param] = $val;
        return $this;
    }

    /**
     * Sugar on top of setParam().
     *
     * Usage: $this->urlTo('foo')->id(123)->foo('bar')->baz('a', 'b', 'c')
     *             ->bat(array('one' => 1, 'two' => 2))->quux();
     *
     * @param string $method
     * @param array  $args
     * @return Crud_SimpleUrl
     */
    public function __call($method, $args)
    {
        $argc = count($args);
        switch ($argc) {
            case 0:
                $val = null;
                break;
            case 1:
                $val = $args[0];
                break;
            default:
                $val = $args;
                break;
        }

        return $this->setParam($method, $val);
    }

    /**
     * Returns the parameter array.
     *
     * @return array
     */
    public function toArray()
    {
        return $this->_params;
    }

    /**
     * Builds the url.
     *
     * @return Zend_View_Helper_Url
     */
    public function __toString()
    {
        return $this->view->url($this->_params, $this->_route, true);
    }

}
